<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>css背景图实现放大镜效果</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .container {
            display: flex;
        }
        .thumbnail {
            width: 640px;
            height: 360px;
            background: url("../image/wallhaven-72g2qo.jpg") 0 0/contain no-repeat;
        }
        .preview {
            width: 200px;
            height: 200px;
            background: url("../image/wallhaven-72g2qo.jpg") 0 0/1920px no-repeat;
        }
    </style>
</head>
<body>
    <blockquote>灵感来源<a href="https://www.bilibili.com/video/BV12N411974Q">S大佬课程</a></blockquote>

    <div class="container">
        <div class="thumbnail"></div>

        <div class="preview"></div>
    </div>

    <script>
        const preview = document.getElementsByClassName("preview")[0];
        document.getElementsByClassName("thumbnail")[0].onmouseenter = function(e) {
            handlePreview(e);
            this.onmousemove = function (e) {
                handlePreview(e);
            };
        };
        function handlePreview(e) {
            const getPos = loc => (-loc * 3 + 100 > 0 ? 0 : -loc * 3 + 100) + "px";

            preview.style.backgroundPositionX = getPos(e.clientX);
            preview.style.backgroundPositionY = getPos(e.clientY);
        }
    </script>
</body>
</html>
